package
{
	import com.pickgliss.toplevel.StageReferance;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Point;
	
	import mx.collections.ArrayCollection;
	import mx.core.UIComponent;
	
	public class ActionPriviewer extends UIComponent
	{
		public function ActionPriviewer()
		{
			super();
		}
		
		private var _container:Sprite;
		private var _bitmap:Bitmap;
		private var _bitmapData:BitmapData;
		private var _guildPoint:Shape;
		
		override protected function createChildren():void
		{
			_container = new Sprite();
			addChild(_container);
			_bitmap = new Bitmap();
			_container.addChild(_bitmap);
			_guildPoint = new Shape();
			_container.addChild(_guildPoint);
			StageReferance.stage.addEventListener(Event.ENTER_FRAME,renderFrame);
			super.createChildren();
		}
		
		private var _currentIndex:int = 0;
		
		private function renderFrame(event:Event):void
		{
			_currentIndex++;
			if(ActionModel.Instance.currentAction.length == 0)return;
			if(_currentIndex >= ActionModel.Instance.currentAction.length)_currentIndex = 0;
			_bitmapData.lock();
			_bitmapData.fillRect(_bitmapData.rect,0x00ff0000);
			
			
			var info:PlistFrameInfo = ActionModel.Instance.currentAction.getItemAt(_currentIndex) as PlistFrameInfo;
			var centerX:Number = _bitmapData.width/2;
			var centerY:Number = _bitmapData.height/2;
			
			var copyPoint:Point = new Point();
			copyPoint.x = centerX + ActionModel.Instance.registerX + info.sourceRect.x;
			copyPoint.y = centerY + ActionModel.Instance.registerY + info.sourceRect.y;
			_bitmapData.copyPixels(ActionModel.Instance.bitmap.bitmapData,info.frameRect,copyPoint);
			_bitmapData.unlock();
		}
		
		override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
		{
			_bitmapData = new BitmapData(unscaledWidth,unscaledHeight,true,0xff0000);
			_bitmap.bitmapData = _bitmapData;
			updateGuildPoint(unscaledWidth,unscaledHeight);
			super.updateDisplayList(unscaledWidth,unscaledHeight);
		}
		
		private function updateGuildPoint(w:int,h:int):void
		{
			_guildPoint.graphics.clear();
			_guildPoint.graphics.lineStyle(1,0xff0000);
			_guildPoint.graphics.moveTo(0,h/2);
			_guildPoint.graphics.lineTo(h,h/2);
			_guildPoint.graphics.moveTo(w/2,0);
			_guildPoint.graphics.lineTo(w/2,h);
		}
	}
}